#include <math.h>
#include <time.h>
#include <stdio.h>
#include <io.h>
#include <opencv2\opencv.hpp>
#include "Gradient.h"
#include "Recognizer.h"
using namespace cv;
using namespace std;


void listdir(const string &fliter,vector<string> &files){
	intptr_t handle;
	struct _finddata_t fileinfo;
	handle = _findfirst(fliter.c_str(), &fileinfo);
	if (-1 == handle)
		return;
	if (strcmp(fileinfo.name, ".") && strcmp(fileinfo.name, "..")){
		files.push_back(fileinfo.name);
	}
	while (!_findnext(handle, &fileinfo))
	{
		if (strcmp(fileinfo.name, ".") && strcmp(fileinfo.name, "..")){
			files.push_back(fileinfo.name);
		}
	}
	_findclose(handle);
}

void split(Recognizer &recognizer, int index, const string &srcPath, const string &outputPath){
	cout << "split:" << srcPath << endl;
	Mat image = imread(srcPath, 1);
	if (fmin(image.cols, image.rows) > 720){
		float scale = 720.0f / (float)fmin(image.cols, image.rows);
		resize(image, image, Size(image.cols*scale, image.rows*scale));
	}
	vector<Mat> subs;
	recognizer.imgSplit(image, subs);
	int i = index;
	for (Mat s : subs){
		imwrite(outputPath+"/"+to_string(i++)+".jpg", s);
	}
}

void preprocess(Recognizer &recognizer){
	int index = 1000;
	vector<string> files;
	listdir("D:/source/opencv/BarcodeGradient/data/material/*", files);
	for (string f : files){
		split(recognizer, index += 1000, "D:/source/opencv/BarcodeGradient/data/material/"+f, "D:/source/opencv/BarcodeGradient/data/output");
	}
}
void train(Recognizer &recognizer){
	vector<string> files;
	listdir("D:/source/opencv/BarcodeGradient/data/barcode/*", files);
	for (string f : files){
		cout << "train:" << "D:/source/opencv/BarcodeGradient/data/barcode/" + f << endl;
		recognizer.train(imread("D:/source/opencv/BarcodeGradient/data/barcode/"+f, 1), true);
	}
	files.clear();
	listdir("D:/source/opencv/BarcodeGradient/data/output/*", files);
	for (string f : files){
		cout << "train:" << "D:/source/opencv/BarcodeGradient/data/output/" + f << endl;
		recognizer.train(imread("D:/source/opencv/BarcodeGradient/data/output/" + f, 1), false);
	}
}

int main()
{
    Recognizer recognizer;
	//preprocess(recognizer);
    //recognizer.setDataInfoPath("data.csv");
    //train(recognizer);
    recognizer.showLineImage(imread("D:/source/opencv/BarcodeGradient/data/material/16.jpg", 1));
    waitKey();
    return 0;
}
